package com.org.gameloft.GLIDER.common;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

/**
 * Created by Claudiu-Florin FILIMON
 * Date: Jul 31, 2007
 * Time: 5:53:44 PM
 * Revision: 0
 */

public final class JarResources
{
    private Hashtable htSizes = new Hashtable();
    private Hashtable htJarContents = new Hashtable();

    private String jarFileName;

    public JarResources(String jarFileName)
    {
        this.jarFileName = jarFileName;
        init();
    }

    public byte[] getResource(String name)
    {
        return (byte[]) htJarContents.get(name);
    }

    private void init()
    {
        try
        {
            // extracts just sizes only.
            ZipFile zf = new ZipFile(jarFileName);
            Enumeration e = zf.entries();
            while (e.hasMoreElements())
            {
                ZipEntry ze = (ZipEntry) e.nextElement();
                htSizes.put(ze.getName(), new Integer((int) ze.getSize()));
            }
            zf.close();

            // extract resources and put them into the hashtable.
            FileInputStream fis = new FileInputStream(jarFileName);
            BufferedInputStream bis = new BufferedInputStream(fis);
            ZipInputStream zis = new ZipInputStream(bis);
            ZipEntry ze;
            while ((ze = zis.getNextEntry()) != null)
            {
                if (ze.isDirectory())
                {
                    continue;
                }
                int size = (int) ze.getSize();
                // -1 means unknown size.
                if (size == -1)
                {
                    size = ((Integer) htSizes.get(ze.getName())).intValue();
                }
                byte[] b = new byte[size];
                int rb = 0;
                int chunk;
                while ((size - rb) > 0)
                {
                    chunk = zis.read(b, rb, size - rb);
                    if (chunk == -1)
                    {
                        break;
                    }
                    rb += chunk;
                }
                // add to internal resource hashtable
                htJarContents.put(ze.getName(), b);
            }

            fis.close();
        }
        catch (NullPointerException e)
        {
            GLLogger.log(e);
        }
        catch (FileNotFoundException e)
        {
            GLLogger.log(e);
        }
        catch (IOException e)
        {
            GLLogger.log(e);
        }
    }
}
